const fs = require('fs');
const path = require('path');
const {organizeStyles, testOrganizeStyles} = require('./整理 less')
const svgJson = require("./svgJson");

const folderPath = './源文件/index.vue'
setFile(folderPath)
// 'theme-02': 'hy-main-alpha-20',
//     'theme-05': 'hy-main-alpha-50',
const color = {
  function: 'hy-main',
  theme: 'hy-main',
  theme02: 'hy-main/20',
  theme05: 'hy-main/50',
  add: 'hy-success',
  success: 'hy-success',
  success05: 'hy-success/50',
  info: 'hy-info',
  prohibit: 'hy-info-alpha-20',
  info05: 'hy-info/50',
  warning: 'hy-warning',
  warning05: 'hy-warning/50',
  danger: 'hy-danger',
  dangerv2: 'hy-danger',
  dangerv205: 'hy-danger/50',
  'c_4477FF': 'text-hy-main',
  'dangerv2-05': 'hy-danger-2-alpha-20',
  main: 'hy-text-main',
  auxiliary: 'hy-text-secondary',
  auxiliaryv2: 'hy-text-secondary-2',
  'background-gradientV2': 'hy-bg-gradient',
  'background-gradient': 'hy-bg-gradient-2',
  background: 'hy-page-bg-1',
  background05: 'hy-page-bg-1/50',
  backgroundv2: 'hy-page-bg-2',
  backgroundv205: 'hy-page-bg-2/50',
  backgroundv3: 'hy-page-bg-3',
  backgroundv305: 'hy-page-bg-3/50',
  backgroundv4: 'hy-page-bg-4',
  backgroundv405: 'hy-page-bg-4/50',
  border: 'hy-border-2',
}
const colorNotFoundList = []
const obj = {
  "centerBox": 'flex items-center justify-center',
  "f-g" :"flex-grow w-0",
  "r-f-i" :"flex",
  "flex_vertically_center":"flex items-center",
  "r-f" :"flex flex-row",
  "c-f-i" :"flex",
  "c-f" :"flex flex-col w-full",
  "tac" :"text-center",
  "tar" :"text-right",
  "ovh" :"overflow-hidden",
  "fl" :"float-left",
  "fr" :"float-right",
  "box_border":"box-border",
  "h_100vh": "h-full",
  "w_100vh": 'w-full',
  "fw_600": 'font-bold',
  "ptb_20": 'py-[20px]',
  "ptb_10": 'py-[10px]',
  "plr_20": 'px-[20px]',
  "plr_10": "px-[10px]",
  "p_20"  : 'p-[20px]',
  "pl_20" : 'pl-[20px]',
  "pr_20" : 'pr-[20px]',
  "pt_20" : 'pt-[20px]',
  "pb_20" : 'pb-[20px]',
  "pl_10" : 'pl-[10px]',
  "pr_10" : 'pr-[10px]',
  "pt_10" : 'pt-[10px]',
  "pb_10" : 'pb-[10px]',
  "mtb_20" : 'my-[20px]',
  "mtb_10" : 'my-[10px]',
  "mlr_20" : 'mx-[20px]',
  "mr_20" : 'mr-[20px]',
  "mt_20" : 'mt-[20px]',
  "mb_20" : 'mb-[20px]',
  "ml_20" : 'ml-[20px]',
  "mr_10" : 'pr-[20px]',
  "mlr_10" : "mx-[10px]",
  "mt_10" : 'mt-[10px]',
  "mb_10" : 'mb-[10px]',
  "ml_10" : 'ml-[10px]',
  "pos_r": 'relative',
  "pos_a" : "absolute",
  "pos_f" : "fixed",
  "h_50" : "h-[50px]",
  "h_80" : "h-[80px]",
  "h_40" : "h-[40px]",
  "h_30" : "h-[30px]",
  "h_20" : "h-[20px]",
  "lh_50" : "leading-[50px]",
  "lh_80" : "leading-[80px]",
  "lh_40" : "leading-[40px]",
  "lh_30" : "leading-[30px]",
  "lh_20" : "leading-[20px]",
  "fs_16" : "text-base",
  "fs_14" : "text-sm",
  "fs_12" : "text-xs",
  "over_one_line": "overflow-ellipsis overflow-hidden whitespace-nowrap",
  "over_one_linev2": "line-clamp-2",
  // "over_one_linev2": "overflow-ellipsis overflow-hidden whitespace-nowrap line-clamp-2",
  "c_fff": "text-hy-text-main",
  "c_theme": "text-hy-main",
  "c_main": "text-hy-text-main",
  "c_info": "text-hy-info",
  "c_auxiliary": "text-hy-text-secondary",
  "c_success": "text-hy-success",
  "c_warning": "text-hy-warning",
  "c_dangerv2": "text-hy-danger",
  "c_2CB954": "text-hy-success",
  "c_888B8F": "text-hy-text-secondary",
  "c_8E9396": "text-hy-text-secondary",
  "c_9DA7B2": "text-hy-text-secondary",
  "c_969696": "text-hy-info",
  "c_D3D3D3": "text-hy-text-main",
  "juzhong": "absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2",
  'css-text-no-select': 'select-none',
  'clickBox': 'click-box'
}

function setFile (path) {
  fs.readFile(path, 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    const commandCenterV3Common = []
    // data = data.replace(new RegExp(/\$\{this.\$t\((\s?\n?\s*?)'(\w*).(\w*)'(\s?\n?\s*?)\)}/, 'g'), (_,a,b,c,d) => {
    //   return `${zh[b][c]}`
    // });
    // data = data.replace(new RegExp(/{{\$t\('(\w*).(\w*)'\)}}/, 'g'), (_,a,b) => {
    //   return `${zh[a][b]}`
    // });
    // data = data.replace(new RegExp(/\$t\('(\w*).(\w*)'\)/, 'g'), (_,a,b) => {
    //   return `'${zh[a][b]}'`
    // });
    data = data.replace(new RegExp('<style[^>]*>([\\s\\S]*?)<\\/style>', 'g'), (match, value) => {
      const res = testOrganizeStyles(match)
      return res.data
    });
    const setCommandCenterV3Common = (name) => {
      const index = commandCenterV3Common.findIndex(v => v === name)
      if (index === -1) {
        commandCenterV3Common.push(name)
      }
    }
    // svg 替换
    data = data.replace(/<svg-icon([\s\S]*?)\/>/g, (match, value) => {
      let type = false
      match = match.replace('className', 'class')
      match = match.replace('class-name', 'class')
      match = match.replace(/svg-name="([\s\S]*?)"/, (_, svgName)=>{
        let svgJsonV = svgJson[`${svgName}`]
        if (svgJsonV) {
          return `name="${svgJsonV}"`
        } else {
          svgJsonV = svgJson[`${svgName.replace(/'([\s\S]*?)'/g, (_svgName, svgName_a) => {
            return svgName_a
          })}`]
          if (svgJsonV) {
            type = true
            return `name="${svgJsonV}"`
          } else {
            console.log('=============', _)
            return _
          }
        }
      })
      match = match.replace(/:svg-name="'([\s\S]*?)'"/, (_, svgName)=>{
        let svgJsonV = svgJson[`${svgName}`]
        if (svgJsonV) {
          return `name="${svgJsonV}"`
        } else {
          svgJsonV = svgJson[`${svgName.replace(/'([\s\S]*?)'/g, (_svgName, svgName_a) => {
            return svgName_a
          })}`]
          if (svgJsonV) {
            type = true
            return `name="${svgJsonV}"`
          } else {
            console.log('=============', _)
            return _
          }
        }
      })
      if (type) {
        match = match.replace(':name', 'name')
      }
      return match
    });
    data = data.replace(/(:?)class="([^"]*)"/g, (match, a, classNames) => {
      // const classes = classNames.split(' ');
      for (const key in color) {
        const regex = new RegExp(`(?<=-)${key}\\b`, 'g');
        match = match.replace(regex, color[key]);
      }
      for (const key in obj) {
        const regex = new RegExp(`\\b${key}\\b`, 'g');
        match = match.replace(regex, obj[key]);
      }
      if (a) {
        match = match.replace(new RegExp(':class="{([\\s\\S]*?):', 'g'), (_,v) => {
          if (v.includes(`'`)) {
            return `:class="{${v}:`
          } else {
            return `:class="{'${v}':`
          }
        })
        match = match.replace(/\s*\n\s*/, '')
      }
      match = match.replace(/-hy-hy-text-main/g, '-hy-main')
      match = match.replace(/box-hy-border-2/g, 'box-border')
      return match
    });

    // iconBox 替换
    data = data.replace(/<iconBox([\s\S]*?)>([\s\S]*?)<\/iconBox>/g, (match, value) => {
      setCommandCenterV3Common('HyRoundButton')
      match = match.replace(/iconBox/g, 'HyRoundButton')
      match = match.replace(/altText/g, 'tips')
      match = match.replace(/classNmae="shadow_delete"/g, 'class="hover:!shadow-hy-danger hover:!border-hy-danger/70" class-name="text-hy-text-danger"')

      match = match.replace(/imgName="([\s\S]*?)"/g, (_, svgName)=>{
        let svgJsonV = svgJson[`${svgName}`]
        if (svgJsonV) {
          return `name="${svgJsonV}"`
        } else {
          svgJsonV = svgJson[`${svgName.replace(/'([\s\S]*?)'/g, (_svgName, svgName_a) => {
            return svgName_a
          })}`]
          if (svgJsonV) {
            return `name="${svgJsonV}"`
          } else {
            console.log('=============', _)
            return _
          }
        }
      })
      return match
    });
    data = data.replace(/style="([\s\S]*?)"/g, (match, value) => {

      if (!value.includes('{')) {
        let text = ``
        value.split('; ').forEach(v => {
          text += `
        ${v};`
        })
        return `class="${organizeStyles(text).data}"`
      } else {
        for (const key in color) {
          const regex = new RegExp(`(?<=-)${key}\\b`, 'g');
          match = match.replace(regex, color[key]);
        }
      }
      return match
    });
    data = data.replace(/<AppTable([\s\S]*?)>([\s\S]*?)<\/AppTable>/g, (match, value) => {
      setCommandCenterV3Common('HyTable')
      match = match.replace('ref="AppTable"', () => {
        if (match.includes('on-select-checkbox')) {
          return `ref="AppTable"
        :selectColumnType="2"
        height="100%"
        :showFooter="true"`
        } else {
          return `ref="AppTable"
        height="100%"
        :showFooter="true"`
        }
      })
      match = match.replace(/<AppTable([\s\S]*?)>/g, (_, a) => {
        _ = _.replace(/orgCascader/g, () => {
          setCommandCenterV3Common('HyOrgCascader')
          return 'HyOrgCascader'
        })
        _ = _.replace(':tableColumns="tableColumns"', ':columnList="tableColumns"')
        _ = _.replace(':requestParams="requestParams"', ':searchForm="requestParams"')
        _ = _.replace('selectParameter', 'select-key')
        _ = _.replace(/controller="([\s\S]*?)"/, (controller, controller_v) => {
          return `reqUrl="${controller_v}/page"`
        })
        _ = _.replace(/@on-select-checkbox="([\s\S]*?)"/, (controller, controller_v) => {
          return `@selection-change="${controller_v}"`
        })
        return _
      })
      match = match.replace(/AppTable/g, 'HyTable')
      match = match.replace('#operator-left-box', '#tableLeft')
      return match
    });

    data = data.replace(/ref="(\w*)"/g,(_,v) => {
      return `ref="${v}Ref"`
    })

    data = data.replace(/ref="HyTableRef"/g,  (_) => {
      return 'ref="AppTableRef"'
    });

    data = data.replace(/(<|<\/)orgCascader/g,  (_) => {
      setCommandCenterV3Common('HyOrgCascader')
      _ = _.replace('orgCascader', 'HyOrgCascader')
      return _
    });

    data = data.replace(/(<[\s\S]*?)>/g,  (v) => {
      let classContent = ''
      let classNum = 0
      v = v.replace(/(:|-?)class="([\s\S]*?)"/g,  (class_v, class_a, class_b) => {
        if(class_v[0] !== ':' && class_v[0] !== '-') {
          classNum++
          if (classNum === 1) {
            classContent += class_b
            return 'aaa'
          } else {
            classContent += ` ${class_b}`
            return ''
          }
        } else {
          return class_v
        }
      });

      if (v.includes('el-button')) {
        if (classContent.includes('button_default')) {
          v = v.replace(/el-button/, `el-button type="primary"`)
          classContent = classContent.replace(/button_default/g, ' ')
        } else if (classContent.includes('button_addTo')) {
          v = v.replace(/el-button/, `el-button type="success"`)
          classContent = classContent.replace(/button_addTo/g, ' ')
        } else if (classContent.includes('button_delete')) {
          v = v.replace(/el-button/, `el-button type="danger"`)
          classContent = classContent.replace(/button_delete/g, ' ')
        }
      } else if (v.includes('svg-icon')) {
        classContent = classContent.replace('svgBox', '')
      }
      if (classContent && classContent.length) {
        classContent = classContent.replace(/\n|\s+/g, ' ')
        v = v.replace(/aaa/, `class="${classContent}"`)
      } else {
        v = v.replace('aaa', '')
      }
      if (v.includes('svg-icon')) {
        let text = ''
        if (!classContent.includes('w-')) {
          text += 'width="16" '
        }
        if (!classContent.includes('w-')) {
          text += 'height="16"'
        }
        v = v.replace('<svg-icon', `<svg-icon ${text}`)
      }
      return v

    });
    /* 处理时间格式转换 */
    data = data.replace(/value-format="([\s\S]*?)"/g,  (v) => {
      v = v.replace('yyyy', 'YYYY')
      v = v.replace('dd', 'DD')
      return v
    });

    data = data.replace(':visible.sync', ':model-value')
    data = data.replace(':picker-options', ':disabled-date')
    data = data.replace(':open-delay', ':show-after')


    data = data.replace(/<div([\s\S]*?)<\/div>/g, (match, value) => {
        if (match.indexOf('requiredTitle') === -1) {
          return  match
        }
        let num = 0
        match.replace(/div/g, (_) => {
          num++
        });
        if (num === 2) {
          if (match.indexOf('popover') === -1) {
            let text =  num
            match.replace(/{{([\s\S]*?)}}/g, (_) => {
            text = _
            return _
          });
            return `<template #label><span class="form-label">${text}</span> </template>`
          }
        }
        return  match
    });

    if (data.indexOf('requiredTitle') !== -1) {
      data = `
       <!-- requiredTitle 出现了代表有表单没有替换 -->
        <!--<template #label> -->
        <!--  <div class="flex items-end justify-between">-->
        <!--    <span class="form-label">{{ $t('department') }}</span>-->
        <!--    <span class="absolute right-0 text-xs click-box text-hy-text-secondary flex items-center">-->
        <!--      {{ $t('addTheDepartment') }}-->
        <!--      <svg-icon width="14" height="14" class-name="ml-1" name="sys-button-add-3" />-->
        <!--    </span>-->
        <!--  </div>-->
        <!--</template>-->
        <!--<template #label>-->
        <!--  {{ $t('department') }}-->
        <!--</template>-->
         ${data}
      `
    }

    let commandCenterV3CommonText = ''
    commandCenterV3Common.forEach((name, index) => {
      commandCenterV3CommonText += index === 0 ? name : `, ${name}`
    })
    fs.writeFile('./结果文件/index.vue', `
     ${commandCenterV3Common.length ? `import { ${commandCenterV3CommonText} } from 'command-center-v3-common'`: ''}
     import { $t } from '@/hooks/use-i18n'
     ${data}
    `, 'utf8', (err) => {
      if (err) {
        console.error(err);
        return;
      }
    });
  });
}
// 读取 SVG 文件
